<% layout('/layouts/default.html', {title: '关键指标展示提交', libs: ['layout', 'dataGrid','inputmask','ueditor','validate']}){ %>
<div class="main-content">
    <div class="box box-main">
        <form class="form-horizontal" id="inputForm">
            <#form:hidden path="examId" value="${dcSupExamVo.examId}"/>
            <#form:hidden path="scoreStatus" value="${dcSupExamVo.dcSupExamScore.scoreStatus}"/>
            <#form:hidden path="exameOrg" value="${dcSupExamVo.exameOrg}"/>
            <div class="box-body">
            <div class="row">
                <div class="form-unit">${text('评分信息')}</div>
            </div>
            <table id="gjDataGrid"></table>
        </div>
            <div class="box-footer">
            <div class="row">
                <div class="col-sm-offset-4 col-sm-8">
                    <% if(dcSupExamVo.dcSupExamScore.scoreStatus == null||dcSupExamVo.dcSupExamScore.scoreStatus!='2'){ %>
                    <button type="submit" class="btn btn-sm btn-primary" id="btnSubmit" onclick="saveGJScore();"><i class="fa fa-check"></i> ${text('提 交')}</button>&nbsp;
                    <% } %>
                    <% if(dcSupExamVo.dcSupExamScore.scoreStatus=='2'){ %>
                    <button class="btn btn-sm btn-danger" id="withdraw" onclick="withDrawGJScore();"> ${text('撤回修改')}</button>&nbsp;
                    <% } %>
                    <button type="button" class="btn btn-sm btn-default btnList" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
                </div>
            </div>
        </div>
        </form>
    </div>
</div>
<% } %>
<script>
    $('#gjDataGrid').dataGrid({
        sortableColumn: true, // 列表不允许排序
        data: ${toJson(dcSupExamVo.dcSupScoreList)},
        datatype: "local", // 设置本地数据
        editGrid: $("#scoreStatus").val()=='',
        showFooter: true, // 是否显示底部合计行
        emptyDataHint: true,
        editGridInitRowNum:0,
        showRownum: false,
        columnModel: [
            {header:'${text("序号")}',sortable:false, name:'sortNum', index:'a.task_title', width:50, align:"center"},
            {header:'${text("任务id")}',hidden: true, name:'examId',width:150, align:"left", frozen:true},
            {header:'${text("主键")}',hidden: true, name:'id',width:150, align:"left", frozen:true},
            {header:'${text("年度")}', name:'examYear', width:80, align:"center",hidden: true},
            {header:'${text("类别")}',sortable:false, name:'quotaType', index:'a.message_number', width:100, align:"center",formatter: function(val, obj, row, act){
                    return js.getDictLabel(${@DictUtils.getDictListJson('dc_quotaType')}, val, '${text("未知")}', true);
                },unformat: function(val, obj, cell){
                return obj.colModel.data[obj.rowId]}},
            {header:'${text("目标内容")}',sortable:false, name:'quotaContent', index:'a.task_type_name', width:350, align:"left" },
            {header:'${text("被考核单位名称")}',hidden: true,sortable:false, name:'exameOrgName', index:'a.task_type_name', width:150, align:"left" },
            {header:'${text("被考核单位编码")}',hidden: true,sortable:false, name:'exameOrg', index:'a.task_type_name', width:150, align:"left" },
            {header:'单位',sortable:false, name:'quotaUnit',width:100, align:"left"},
            {header:'${text("本年度目标")}',sortable:false, name:'currentYaerGoal', index:'a.task_type_name', width:100, align:"left" },
            {header:'权数',sortable:false, name:'quotaWeight',  width:120, align:"center",
                formatter: function(val, obj, row, act){
                    if (val==null||val==''){val=0;}
                    return parseFloat(val).toFixed(2);
                }
            },
            {header:'${text("考核方式")}', name:'assessMethod', width:130, align:"left", formatter: function(val, obj, row, act){
                    return js.getDictLabel(${@DictUtils.getDictListJson('dc_exam_assessment')}, val, '', true);
                }},

            {header:'百分比得分', name:'percentage', width:120,edittype:'text',editable:true, align:"center",editoptions:{'class':'form-control required',
                    dataInit: function(element){
                        let rowid=$(element).attr("rowid")
                        let data=$('#gjDataGrid').dataGrid('getRowData', rowid);
                        $(element).attr("inputvalidate","score")
                        $(element).addClass('inputmask').attr({'data-inputmask-alias': "money", 'data-inputmask': "'digits':'2'",'range':'[0,120]'}).inputmask()
                        $(element).on("input",function (e){
                            let inputVal= $(element).val();
                            let quotaScore= (parseFloat(inputVal)/100)*data.quotaWeight;
                            $("#gjDataGrid").jqGrid("setCell",rowid,"quotaScore",roundHalfUp(quotaScore,3));
                            refreshZpCount();
                        })
                        $(element).wrapAll("<div class='input-group'></div>")
                        $(element).after('<span class="input-group-addon">%</span>')

                    }
            },unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();},
                formatter: function(val, obj, row, act){
                    if (val==''||typeof val=="undefined"){val=0;}
                    return val.toFixed(2)+"%";
            }},
            {header: "分数",name: 'quotaScore',width: 70,align: 'center',editable:false,editoptions:{'class':'form-control required',
               dataInit: function(element){
                        // let rowid=$(element).attr("rowid")
                        // let data=$('#gjDataGrid').dataGrid('getRowData', rowid);
                        // $(element).attr("inputvalidate","score")
                        // $(element).addClass('inputmask').attr({'data-inputmask-alias': "money", 'data-inputmask': "'digits':'3'",'range':'[0,'+data.quotaWeight+']'}).inputmask()
                        // $(element).on("input",function (){
                        //     let inputVal= $(element).val();
                        //     let percentage=(inputVal/parseFloat(data.quotaWeight))*100;
                        //     $("#"+rowid+"_percentage").val(roundHalfUp(percentage,2))
                        //     refreshZpCount();
                        // })
                    }
                },
                formatter: function(val, obj, row, act){
                    if (val==''||typeof val=="undefined"){val=0;}
                    return parseFloat(val).toFixed(3);
                },
                unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();
            }},
            {header:'备注', name:'scoreReason', width:150, align:"left",classes:'autoHH',
                editable:true, edittype:'text', editoptions:{'maxlength':'200','placeholder':'备注，限制200字以内','autocomplete':'off','class':'form-control',
                    dataInit:function (element){

                    }
                }, unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}
            },

        ],
        onSelectRow: function(id, isSelect, event){

        },
        ajaxSuccess: function(data){
            refreshZpCount();
        }
    });


    function refreshZpCount(){
        let data = $('#gjDataGrid').dataGrid('getRowData');
        let allQuotaWeight=0.0;
        let allQuotaScore=0.0;
        for (let i = 0; i < data.length; i++) {
            if (data[i].quotaScore == 'undefined' ||data[i].quotaScore==''){
                continue;
            }
            allQuotaWeight=accAdd(parseFloat(data[i].quotaWeight||0),allQuotaWeight);
            allQuotaScore=accAdd(parseFloat(data[i].quotaScore||0),allQuotaScore);
        }
        $('#gjDataGrid').dataGrid("footerData", "set", {
            "quotaUnit" : "<center><span>汇总：</span></center>",
            "quotaWeight" : "总权数<span>&nbsp;"+parseFloat(allQuotaWeight).toFixed(2)+" &nbsp;</span>分",
            "quotaScore": "总分<span>&nbsp;"+parseFloat(allQuotaScore).toFixed(3)+" &nbsp;</span>分"
        }, false);
    }

    function saveGJScore(){
        $("#inputForm").validate({
            submitHandler: function(){
                let html=$('#gjDataGrid').find('input[inputvalidate=score]');
                let hasValid=true;
                for (let i = 0; i <html.length; i++) {
                    let has= $("#inputForm").validate().element(html[i]);
                    if (has==false){hasValid=false}
                }
                if (hasValid){
                    saveScore();
                }
            }
        });
    }

    function saveScore(){
        //评分数据为空禁止提交评分
        let rowData=$('#gjDataGrid').dataGrid('getRowData');
        if (rowData==null || rowData.length==0){
            js.alert('当前指标列表为空禁止提交分数！', {icon: 2}, function(){})
            return;
        }
        let allData =JSON.stringify(rowData);
        let subData = {
            "dcSupExamSumQuotaDtoListStr":allData,
            "examId":$("#examId").val(),
            "exameOrg":$("#exameOrg").val()
        };
        js.ajaxSubmit({url:"${ctx}/score/dcSupExamGJZBScore/saveGJScore",data:subData,dataType: 'json',callback:function (data){
                if (data.result=="true"){
                    js.showMessage(data.message);
                    let url= js.addParam(js.removeParam("selectExamOrg",window.parent.location.href),"&selectExamOrg="+subData.exameOrg);
                    window.parent.location.replace(url);
                }else {
                    js.showMessage(data.message);
                }
        }})
    }

    function withDrawGJScore() {
        $.ajax({
            url: "${ctx}/score/dcSupExamGJZBScore/withDrawGJScore",
            type: "post",
            cache: false,
            async:false,
            data: {
                "examId":$("#examId").val(),
                "exameOrg":$("#exameOrg").val()
            },
            success: function(data){
                js.showMessage(data.message);
                let url= js.addParam(js.removeParam("selectExamOrg",window.parent.location.href),"&selectExamOrg="+subData.exameOrg);
                window.parent.location.replace(url);
            }
        });
    }
    function accAdd(arg1,arg2){
        let r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2))
        return (arg1*m+arg2*m)/m
    }

    function accSub(arg1,arg2){
        let r1,r2,m,n;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2));
        //last modify by deeka
        //动态控制精度长度
        n=(r1>=r2)?r1:r2;
        return ((arg1*m-arg2*m)/m).toFixed(n);
    }

    //四舍五入并且保留几位小数
    function roundHalfUp(num, n) {
        n = n ? parseInt(n) : 0;
        if(n <= 0) {
            return Math.round(num);
        }
        num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
        num = Number(num).toFixed(n); //补足位数
        return num;
    }
</script>

<style>
    .ui-layout-content{
        padding: 0px !important;
    }
    .autoHH{
        white-space: normal !important;
        height:auto;
        /*vertical-align:text-top;*/
        padding-top:2px;
        word-break:break-all;
    }
</style>

